package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 登录功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        Map map = new HashMap();
        //校验是否登录
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //根据手机号查询apuser表
//            LambdaQueryWrapper<ApUser> queryWrapper = Wrappers.lambdaQuery();
//            queryWrapper.eq(ApUser::getPhone,dto.getPhone());
//            ApUser apUser = getOne(queryWrapper);
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            //如果不存在，返回错误信息
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //如果存在，校验密码
            String password = dto.getPassword();
            String salt = apUser.getSalt();
            //对明文进行加密
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //如果密码错误，返回错误信息
            if (!pwd.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR );
            }
            //如果密码正确，表示登录成功。生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());

            //封装数据

            map.put("token",token);
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user",apUser);
        }else {
            //不登陆先看看

            //直接返回token，id=0L
            String token = AppJwtUtil.getToken(0L);

            map.put("token",token);
        }


        return ResponseResult.okResult(map);
    }
}
